using CR.API.Services;
using CR.Domain.Entities;
using CR.ErrorCode;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace CR.API.Controllers
{
    /// <summary>
    /// 身份认证控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ICaptchaService _captchaService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userService">用户服务</param>
        /// <param name="captchaService">验证码服务</param>
        public AuthController(IUserService userService, ICaptchaService captchaService)
        {
            _userService = userService;
            _captchaService = captchaService;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns>验证码ID和图片URL</returns>
        [HttpGet("captcha")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResult<object>>> GetCaptcha()
        {
            try
            {
                var (captchaId, imageUrl) = await _captchaService.GenerateCaptchaAsync();

                return Ok(ApiResult<object>.Success(new
                {
                    CaptchaId = captchaId,
                    ImageUrl = imageUrl
                }));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult<object>.Fail(ApiEnums.SystemError, $"获取验证码失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">登录请求</param>
        /// <returns>登录结果</returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResult<string>>> Login([FromBody] LoginRequest request)
        {
            if (request == null)
            {
                return BadRequest(ApiResult<string>.Fail(ApiEnums.ParameterError, "请求参数无效"));
            }

            var result = await _userService.LoginAsync(
                request.Username, 
                request.Password, 
                request.CaptchaId, 
                request.CaptchaCode);

            if (result.Code == 0)
            {
                return Ok(result);
            }

            return BadRequest(result);
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="request">注册请求</param>
        /// <returns>注册结果</returns>
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResult<User>>> Register([FromBody] RegisterRequest request)
        {
            if (request == null)
            {
                return BadRequest(ApiResult<User>.Fail(ApiEnums.ParameterError, "请求参数无效"));
            }

            var user = new User
            {
                Username = request.Username,
                Email = request.Email,
                RealName = request.RealName,
                PhoneNumber = request.PhoneNumber,
                Role = "User" // 默认为普通用户角色
            };

            var result = await _userService.RegisterAsync(user, request.Password);

            if (result.Code == 0)
            {
                return Ok(result);
            }

            return BadRequest(result);
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns>当前用户信息</returns>
        [HttpGet("user")]
        [Authorize]
        public async Task<ActionResult<ApiResult<object>>> GetCurrentUser()
        {
            var user = await _userService.GetCurrentUserAsync();
            if (user == null)
            {
                return Unauthorized(ApiResult<object>.Fail(ApiEnums.Unauthorized, "未授权"));
            }

            // 清除敏感信息
            user.PasswordHash = null;

            return Ok(ApiResult<object>.Success(new
            {
                user.Id,
                user.Username,
                user.Email,
                user.RealName,
                user.PhoneNumber,
                user.Role,
                user.LastLoginTime
            }));
        }
        
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="request">修改密码请求</param>
        /// <returns>修改结果</returns>
        [HttpPost("change-password")]
        [Authorize]
        public async Task<ActionResult<ApiResult>> ChangePassword([FromBody] ChangePasswordRequest request)
        {
            if (request == null)
            {
                return BadRequest(ApiResult.Fail(ApiEnums.ParameterError, "请求参数无效"));
            }

            var userId = int.Parse(User.FindFirst("uid")?.Value);
            var result = await _userService.ChangePasswordAsync(userId, request.OldPassword, request.NewPassword);

            if (result.Code == 0)
            {
                return Ok(result);
            }

            return BadRequest(result);
        }
    }

    /// <summary>
    /// 登录请求
    /// </summary>
    public class LoginRequest
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string Username { get; set; }
        
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
        
        /// <summary>
        /// 验证码ID
        /// </summary>
        public string CaptchaId { get; set; }
        
        /// <summary>
        /// 验证码
        /// </summary>
        public string CaptchaCode { get; set; }
    }

    /// <summary>
    /// 注册请求
    /// </summary>
    public class RegisterRequest
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string Username { get; set; }
        
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
        
        /// <summary>
        /// 电子邮箱
        /// </summary>
        public string Email { get; set; }
        
        /// <summary>
        /// 真实姓名
        /// </summary>
        public string RealName { get; set; }
        
        /// <summary>
        /// 手机号码
        /// </summary>
        public string PhoneNumber { get; set; }
    }

    /// <summary>
    /// 修改密码请求
    /// </summary>
    public class ChangePasswordRequest
    {
        /// <summary>
        /// 旧密码
        /// </summary>
        public string OldPassword { get; set; }
        
        /// <summary>
        /// 新密码
        /// </summary>
        public string NewPassword { get; set; }
    }
} 